package com.heima.media.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmSensitiveService wmSensitiveService;

    @GetMapping("/audit/{id}")
    public ResponseResult audit(@PathVariable("id") Integer id) {
        auditService.audit(id);
        return ResponseResult.okResult();
    }


    //从excel中读取敏感词更新到数据库
    @PostMapping("/uploadExcel")
    public ResponseResult uploadExcel(MultipartFile file) throws Exception {

        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            for (WmSensitive wmSensitive : dataList) {
                LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmSensitive::getSensitives, wmSensitive.getSensitives());
                if (wmSensitiveService.count(queryWrapper) == 0) {
                    wmSensitive.setCreatedTime(new Date());
                    wmSensitiveService.save(wmSensitive);
                }
            }
        })).sheet().doRead();
        return ResponseResult.okResult();
    }


    //读取数据库写入到excel中
    @GetMapping("/downloadExcel")
    public ResponseResult downloadExcel(HttpServletResponse response) throws Exception {
        List<WmSensitive> list = wmSensitiveService.list();

        //一个流，两个头
        response.addHeader("Content-Disposition", "attachment;filename=sensitive.xlsx");
        response.setContentType("text/html");

        EasyExcel.write(response.getOutputStream(),WmSensitive.class).sheet("敏感词").doWrite(list);

        return ResponseResult.okResult();
    }

}
